package com.unittec.drainage.provider.manage.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.drainage.provider.common.RedisUtils;
import com.unittec.drainage.provider.manage.constans.ManageConstans;
import com.unittec.drainage.provider.manage.entity.Region;
import com.unittec.drainage.provider.manage.dto.WaterheadUserDto;
import com.unittec.drainage.provider.manage.entity.WaterheadFeeCollection;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.utils.CopyUtils;
import com.unittec.drainage.provider.utils.UUIDUtils;
import com.unittec.drainage.sdk.auth.domain.SysUserInfo;
import com.unittec.drainage.sdk.auth.request.Req101135;
import com.unittec.drainage.sdk.manage.request.*;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.internal.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.drainage.provider.manage.entity.WaterheadUser;
import com.unittec.drainage.provider.manage.mapper.WaterheadUserMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Jason
 * @date 2021/8/11
 */
@Service
@Transactional
public class WaterheadUserService extends ServiceImpl<WaterheadUserMapper, WaterheadUser> {

    @Resource
    private RegionService regionService;

    @Resource
    private WaterheadFeeCollectionService waterheadFeeCollectionService;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private UserService userService;

    /**
     * 添加水源用户
     * @param req301100
     */
    public void addWaterheadUser(Req301100 req301100) {
        if(Integer.parseInt(req301100.getUserCode().substring(2))<Integer.parseInt(redisUtils.get("code"+req301100.getWaterheadType()))){
            throw new BusinessException("当前操作人数较多，请重新获取用户代码后再进行操作");
        }
        if(!req301100.getPriceCategory().equals(req301100.getLevyStandard())){
            throw new BusinessException("征收标准和污水价类别应该相等");
        }
        String id = UUIDUtils.getId();
        WaterheadUser waterheadUser = new WaterheadUser();
        CopyUtils.copyProperties(req301100, waterheadUser);
        waterheadUser.setId(id);
        ThreadLocalScope.AuthData authData = ThreadLocalScope.getAuthData();
        waterheadUser.setOpneName(authData.getUserName());
        waterheadUser.setOpneBy(authData.getUser());
        //立户时间
        String l = String.valueOf(System.currentTimeMillis());
        waterheadUser.setOpneTime(new Date(Long.valueOf(l.substring(0,l.length()-3)+"000")));
        this.save(waterheadUser);
        redisUtils.incr("code"+req301100.getWaterheadType());
    }

    /**
     * 水源用户编辑
     * @param req301101
     */
    public void updateWaterheadUser(Req301101 req301101) {
        //已经销户的用户不能编辑
        WaterheadUser waterheadUser = this.getById(req301101.getId());
        if("1".equals(waterheadUser.getState())){
            throw new BusinessException("该用户已销户，不能对其修改");
        }
        if(waterheadUser == null){
            throw new BusinessException("该用户id不存在");
        }
        CopyUtils.copyProperties(req301101,waterheadUser);
        this.updateById(waterheadUser);
    }

    /**
     * 水源用户销户
     * @param req301102
     */
    public void delWaterheadUser(Req301102 req301102) {
        //如果有污水费则必须先完成支付才能销户
        LambdaQueryWrapper<?> qw = new LambdaQueryWrapper<>();
        StringBuilder ids = new StringBuilder();
        for (String id : req301102.getIds()) {
            ids.append("'"+id+"'"+",");
        }
        if(ids.length()>0){
            ids.deleteCharAt(ids.length()-1);
        }
        qw.apply("a.waterhead_user_id in ("+ids+")");
        List<Map<String, Object>> userNotPay = this.baseMapper.getUserNotPay(qw);
        if (userNotPay.size()>0){
            StringBuilder mess = new StringBuilder();
            for (Map<String, Object> sop : userNotPay) {
                if (!sop.get("sum").toString().equals("0")) {
                    mess.append(sop.get("user_name") + "有" + sop.get("sum") + "笔污水费未支付,");
                }
            }
            mess.deleteCharAt(mess.length()-1);
            throw new BusinessException(mess.toString());
        }
        List<WaterheadUser> waterheadUsers = this.listByIds(req301102.getIds());
        for (WaterheadUser waterheadUser : waterheadUsers) {
            if ("1".equals(waterheadUser.getState())) {
                throw new BusinessException(waterheadUser.getUserName() + "已经销户，无需重复销户");
            }
            waterheadUser.setState("1");
            waterheadUser.setCloseTime(new Date(System.currentTimeMillis()));
            waterheadUser.setCloseBy(ThreadLocalScope.getAuthData().getUser());
        }
        this.updateBatchById(waterheadUsers);
    }

    /**
     * 水源用户详情
     * @param req301103
     * @return
     */
    public WaterheadUserDto getWaterheadUserInfo(Req301103 req301103) {
        WaterheadUser waterheadUser = this.getById(req301103.getId());
        WaterheadUserDto waterheadUserDto = new WaterheadUserDto();
        CopyUtils.copyProperties(waterheadUser, waterheadUserDto);
        //查询用户的完整水系
        LambdaQueryWrapper<Object> lqw = new LambdaQueryWrapper<>();
        lqw.apply("id = '" + waterheadUser.getRiverSystemId() + "'");
        List<String> names = this.baseMapper.getAllRegionById(lqw);
        Collections.reverse(names);
        String join = String.join("/", names);
        waterheadUserDto.setRiverSystem(join);
        //查询完整区域
        lqw.clear();
        String id = StrUtil.isNotBlank(waterheadUser.getCommunityId()) ? waterheadUser.getCommunityId() : StrUtil.isNotBlank(waterheadUser.getRoadId()) ? waterheadUser.getRoadId() : waterheadUser.getRegionId();
        lqw.apply("id = '" + id + "'");
        List<String> rnames = this.baseMapper.getAllRegionById(lqw);
        Collections.reverse(rnames);
        String join1 = String.join("/", rnames);
        waterheadUserDto.setRegion(join1);
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        try {
            waterheadUserDto.setOpneName(usersMap.get(waterheadUser.getCreateUser()).getRealname());
            waterheadUserDto.setCloseName(usersMap.get(waterheadUser.getCloseBy()).getRealname());
        }catch (Exception e){}
        return waterheadUserDto;
    }

    /**
     * 水源用户条件分页查询
     * @param req301105
     * @return
     */
    public IPage getWaterheadUserPage(Req301105 req301105) {
        LambdaQueryWrapper<WaterheadUser> lqw = new LambdaQueryWrapper<>();
        //水源类型
        if(StringUtils.isNotBlank(req301105.getWaterhead_type())){
            lqw.eq(WaterheadUser::getWaterheadType,req301105.getWaterhead_type());
        }
        //用户代码
        if(StringUtils.isNotBlank(req301105.getUserCode())){
            lqw.like(WaterheadUser::getUserCode,req301105.getUserCode());
        }
        //用户名称
        if(StringUtils.isNotBlank(req301105.getUserName())){
            lqw.like(WaterheadUser::getUserName,req301105.getUserName());
        }
        //用户地址
        if(StringUtils.isNotBlank(req301105.getUserAddress())){
            lqw.like(WaterheadUser::getUserAddress,req301105.getUserAddress());
        }
        //用户电话
        if(StringUtils.isNotBlank(req301105.getUserPhone())){
            lqw.like(WaterheadUser::getUserPhone,req301105.getUserPhone());
        }
        //用户状态
        if(StringUtils.isNotBlank(req301105.getState())){
            lqw.eq(WaterheadUser::getState,req301105.getState());
        }
        //用水性质
        if(StringUtils.isNotBlank(req301105.getWaterNature())){
            lqw.eq(WaterheadUser::getWaterNature,req301105.getWaterNature());
        }
        //水系id ,和该id下所有子水系区域
        if(StringUtils.isNotBlank(req301105.getRiverSystemId())){
            //先查询对应水系下的所有子级水系id
            List<Region> regionSonIds = this.baseMapper.getRegionSonIds(new LambdaQueryWrapper<>().apply("t1.id = '" + req301105.getRiverSystemId() + "'"));
            List<String> idSet = new ArrayList<>();
            for(Region r : regionSonIds){
                idSet.add(r.getId());
            }
            lqw.in(WaterheadUser::getRiverSystemId,idSet);
        }
        //行政区域id
        if(StringUtils.isNotBlank(req301105.getRegionId())){
            lqw.eq(WaterheadUser::getRegionId,req301105.getRegionId());
        }
        //排序
        lqw.orderByDesc(WaterheadUser::getCreateTime);
        Page<WaterheadUser> waterheadUserPage = new Page<>(req301105.getCurrent(), req301105.getSize());
        IPage<Map<String, Object>> userPage = this.baseMapper.getUserPage(waterheadUserPage, lqw);
        return userPage;
    }

    public List<Map<String, Object>> getWaterheadUserList(Req301104 req301104) {
        LambdaQueryWrapper<WaterheadUser> lqw = new LambdaQueryWrapper<>();
        //水源类型
        if(StringUtils.isNotBlank(req301104.getWaterheadType())){
            lqw.eq(WaterheadUser::getWaterheadType,req301104.getWaterheadType());
        }
        //用户代码
        if(StringUtils.isNotBlank(req301104.getUserCode())){
            lqw.like(WaterheadUser::getUserCode,req301104.getUserCode());
        }
        //用户名称
        if(StringUtils.isNotBlank(req301104.getUserName())){
            lqw.like(WaterheadUser::getUserName,req301104.getUserName());
        }
        //用户地址
        if(StringUtils.isNotBlank(req301104.getUserAddress())){
            lqw.like(WaterheadUser::getUserAddress,req301104.getUserAddress());
        }
        //用户电话
        if(StringUtils.isNotBlank(req301104.getUserPhone())){
            lqw.like(WaterheadUser::getUserPhone,req301104.getUserPhone());
        }
        //用户状态
        if(StringUtils.isNotBlank(req301104.getState())){
            lqw.eq(WaterheadUser::getState,req301104.getState());
        }
        //用水性质
        if(StringUtils.isNotBlank(req301104.getWaterNature())){
            lqw.eq(WaterheadUser::getWaterNature,req301104.getWaterNature());
        }
        //水系id ,和该id下所有子水系区域
        if(StringUtils.isNotBlank(req301104.getRiverSystemId())){
            //先查询对应水系下的所有子级水系id
            List<Region> regionSonIds = this.baseMapper.getRegionSonIds(new LambdaQueryWrapper<>().apply("t1.id = '" + req301104.getRiverSystemId() + "'"));
            List<String> idSet = new ArrayList<>();
            for(Region r : regionSonIds){
                idSet.add(r.getId());
            }
            lqw.in(WaterheadUser::getRiverSystemId,idSet);
        }
        //行政区域id
        if(StringUtils.isNotBlank(req301104.getRegionId())){
            lqw.eq(WaterheadUser::getRegionId,req301104.getRegionId());
        }
        //排序
        lqw.orderByDesc(WaterheadUser::getCreateTime);
        return this.baseMapper.getUserPage(lqw);
    }

    /**
     * 自动生成用户代码
     * @param req301121
     * @return
     */
    public synchronized String autoGenWaterheadUserCode(Req301121 req301121) {
        String code;
        //从redis读取code
        code = redisUtils.get("code"+req301121.getWaterheadType());
        //如果缓存中没有code
        if(StringUtils.isBlank(code)){
            //从数据库查询出最大的code
            LambdaQueryWrapper<WaterheadUser> qw = new LambdaQueryWrapper<>();
            qw.eq(WaterheadUser::getWaterheadType,req301121.getWaterheadType());
            List<WaterheadUser> list1 = this.list(qw);
            int max = 0;//如果数据库没有数据则默认是00001
            for (WaterheadUser waterheadUser : list1) {
                int i = Integer.parseInt(waterheadUser.getUserCode().substring(2));
                max = i > max ? i : max;
            }
            code = max + 1 + "";
            //把max存入缓存
            redisUtils.set("code"+req301121.getWaterheadType(), code);
        }
        //左边补0到5位
        code = StringUtils.leftPad(code,5,'0');
        if("1".equals(req301121.getWaterheadType())){
            code = "ZB" + code;
        }else{
            code = "JZ" + code;
        }
        return code;
    }

    /**
     * 根据用户代码查看用户详情
     * @param req301122
     * @return
     */
    public WaterheadUser getWaterheadUserByCode(Req301122 req301122) {
        LambdaQueryWrapper<WaterheadUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WaterheadUser::getUserCode,req301122.getUserCode());
        return this.getOne(lambdaQueryWrapper);
    }

    /**
     * 根据用户代码模糊查询用户代码
     * @param req301124
     * @return
     */
    public Object getCodeByCode(Req301124 req301124) {
        LambdaQueryWrapper<WaterheadUser> lqw = new LambdaQueryWrapper<>();
        //必须未对应的水源类型的用户
        lqw.eq(WaterheadUser::getWaterheadType,req301124.getWaterheadType());
        if(StringUtils.isNotBlank(req301124.getCode())){
            lqw.like(WaterheadUser::getUserCode,req301124.getCode());
        }
        //已销户的排除
        lqw.eq(WaterheadUser::getState,"0");
        List<WaterheadUser> list = this.list(lqw);
        List<HashMap<String, String>> maps = new ArrayList<>();
        for (WaterheadUser waterheadUser : list) {
            HashMap<String, String> map = new HashMap<>();
            map.put("id",waterheadUser.getId());
            map.put("code",waterheadUser.getUserCode());
            maps.add(map);
        }
        return maps;
    }
}
